<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom: 10px" type="text" prefix-icon="el-icon-search"
          size="small" placeholder="输入员工姓名全员搜索" @input="chanageValue" />
        <!-- 树形组件 -->
        <el-tree ref="deptTree" node-key="id" :data="depts" :props="defaultProps" default-expand-all
          :expand-on-click-node="false" highlight-current @current-change="selectNode" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <span style="margin-right: 64%">
            <el-button type="primary" size="mini" @click="OpenDialog">群发通知</el-button>
          </span>
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable width="120px" />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left: 10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination layout="total,prev, pager, next" :total="total" :current-page="queryParams.pageNum"
            :page-size="queryParams.pageSize" @current-change="changePage" />
        </el-row>
      </div>
    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{
          item.name
        }}</el-checkbox>
      </el-checkbox-group>
      <!-- 确定和取消按钮 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog title="群发通知" :visible.sync="dialogFormVisible">
      <el-form :model="form">

        <el-form-item label="活动名称" :label-width="formLabelWidth">
          <div style="border: 0.2mm solid #cccccc; border-radius: 10px; padding: 5px;">
            <el-tag :key="user.id" v-for="user in users" closable :disable-transitions="false"
              @close="handleClose(user.id)">
              {{ user.username }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="通知类型" :label-width="formLabelWidth">
          <el-select v-model="form.message" placeholder="请选择通知类型">
            <el-option label="通知消息" value="1"></el-option>
            <el-option label="提示消息" value="2"></el-option>
            <el-option label="重要消息" value="3"></el-option>
            <el-option label="紧急消息" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通知内容" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form.content" placeholder="请输入通知内容"></el-input>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendDataToServer">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from "@/api/department.js";

import {
  getEmployeeList,
  exportEmployee,
  delEmployee,
  getEmployeeDetail,
  assignRole,
} from "@/api/employee.js";
import { getEnableRoleList } from "@/api/role";
import { transListToTreeData } from "@/utils";
import FileSaver from "file-saver";
import { mapGetters } from 'vuex'
import ImportExcel from "./components/import-excel.vue";

export default {
  name: "Employee",
  components: {
    ImportExcel,
  },
  computed: {
    ...mapGetters([ "userInfo","employInfo"])// 使用 mapGetters 获取 getUserInfo 函数
  },
  data() {
    return {
      // ws是否启动
      wsIsRun: false,
      // 定义ws对象
      webSocket: {},
      // ws请求链接（类似于ws后台地址）
      ws: '',
      // ws定时器
      wsTimer: null,
      roleList: [], // 接收角色列表
      roleIds: [5], // 用来双向绑定数据的
      showRoleDialog: false,
      currentUserId: null, // 用来记录当前点击的用户id
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      depts: [], // 组织数据
      dialogFormVisible: false,// 分发消息对话框显示数据
      defaultProps: {
        label: "name",
        children: "children",
      },
      users: [ /* 数据数组 */],
      form: {
        content: '',
        message: ''
      },
      wsuri: 'ws://localhost:8989/websocket/11',
      formLabelWidth: '120px',
      ids: [], // 用来存储选中的用户id
      //储存查询参数
      message: '',
      queryParams: {
        departmentId: null,
        pageNum: 1, // 当前页码
        pageSize: 5,
        keyword: "", // 模糊搜索字段
      },
      total: 0,
      list: [],
    };
  },
  created() {
    console.log(this.userInfo)
    console.log(this.employInfo.mobile)
    this.getDepartment();
    this.getEmployeeList();
    this.wsIsRun = true
    this.wsInit()
    console.log(this.$globalVar);
  },

  methods: {
    OpenDialog() {
      this.dialogFormVisible = true;
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    handleSelectionChange(selection) {
      // 处理选择发生变化的事件
      console.log('当前的选择：', selection);
      this.users = selection
      this.ids = this.users.map((user) => user.mobile).join(",");
      // 选中的用户id
      // this.ids = this.users.map((user) => user.id).join(",");
      console.log(this.ids)
    },
    sendDataToServer() {
      this.dialogFormVisible = false
      //     this.users.forEach(user => {
      //   user.key = user.id; // 设置用户对象的key属性为id值
      //   this.dynamicTags.push(user);
      // });
      // this.wsDestroy()
      // this.ws = this.wsuri + "," + this.ids

      // this.webSocket = new WebSocket(this.ws)

      // clearInterval(this.wsTimer)
      // this.wsTimer = setInterval(() => {
      //   if (this.webSocket.readyState === 1) {
      //     clearInterval(this.wsTimer)
      //   } else {
      //     console.log(this.webSocket.readyState, "this.webSocket.readyState")
      //     console.log('ws建立连接失败')
      //     // this.wsInit()
      //   }
      // }, 3000)
      // this.$globalVar.$emit('custom-event', this.message)


      if (this.webSocket.readyState === 1) {
        this.webSocket.send(this.ids + "||" + this.form.content)
      } else {
        throw Error('服务未连接')
        // this.webSocket.send(this.form.content)
      }
    },
    /**
     * 初始化ws
     */
    wsInit() {
      // console.log(this.ids)

        // const wsuri = 'ws://localhost:8989/websocket/'+this.ids
        const wsuri = 'ws://localhost:8989/websocket/' + this.employInfo.mobile
        this.ws = wsuri
        if (!this.wsIsRun) return
        // 销毁ws
        // this.wsDestroy()
        // 初始化ws
        this.webSocket = new WebSocket(wsuri)
        // ws连接建立时触发
        this.webSocket.addEventListener('open', this.wsOpenHanler)
        // ws服务端给客户端推送消息
        this.webSocket.addEventListener('message', this.wsMessageHanler)
        // ws通信发生错误时触发
        this.webSocket.addEventListener('error', this.wsErrorHanler)
        // ws关闭时触发
        this.webSocket.addEventListener('close', this.wsCloseHanler)
        // 检查ws连接状态,readyState值为0表示尚未连接，1表示建立连接，2正在关闭连接，3已经关闭或无法打开
        clearInterval(this.wsTimer)
        this.wsTimer = setInterval(() => {
          if (this.webSocket.readyState === 1) {
            clearInterval(this.wsTimer)
          } else {
            console.log(this.webSocket.readyState, "this.webSocket.readyState")
            console.log('ws建立连接失败')
            this.wsInit()
          }
        }, 3000)


    },

    wsOpenHanler(event) {
      console.log('ws建立连接成功')
    },
    wsMessageHanler(e) {
      console.log('wsMessageHanler')
      console.log(e)
      console.log(e.data)
      this.message = e.data
      this.$globalVar.$emit('custom-event', this.message)
      // const redata = JSON.parse(e.data)
      // console.log(redata)
    },
    /**
     * ws通信发生错误
     */
    wsErrorHanler(event) {
      console.log(event, '通信发生错误')
      this.wsInit()
    },
    /**
     * ws关闭
     */
    wsCloseHanler(event) {
      console.log(event, 'ws关闭')
      this.wsInit()
    },
    /**
     * 销毁ws
     */
    wsDestroy() {
      if (this.webSocket !== null) {
        this.webSocket.removeEventListener('open', this.wsOpenHanler)
        this.webSocket.removeEventListener('message', this.wsMessageHanler)
        this.webSocket.removeEventListener('error', this.wsErrorHanler)
        this.webSocket.removeEventListener('close', this.wsCloseHanler)
        this.webSocket.close()
        this.webSocket = null
        clearInterval(this.wsTimer)
      }
    },
    async getDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      this.depts = transListToTreeData(await getDepartment(), 0);
      this.queryParams.departmentId = this.depts[0].id;
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId);
      });
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id; // 重新记录了参数
      this.queryParams.pageNum = 1; // 设置第一页
      if (this.queryParams.departmentId === 1) {
        this.queryParams.departmentId = null;
        this.getDepartment();
      }
      this.getEmployeeList();
    },
    async getEmployeeList() {
      const result = await getEmployeeList(this.queryParams);
      this.list = result.list;
      this.total = result.total;
    },
    changePage(newPage) {
      this.queryParams.pageNum = newPage; // 赋值新页码
      this.queryParams.departmentId = null;
      this.getEmployeeList(); // 查询数据
    },
    chanageValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer); // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.pageNum = 1;
        this.queryParams.departmentId = null;
        this.getEmployeeList();
      }, 300);
    },
    async exportEmployee() {
      const result = await exportEmployee();
      FileSaver.saveAs(result, "员工信息表.xlsx"); // 下载文件
    },
    async confirmDel(id) {
      await delEmployee(id);
      if (this.list.length === 1 && this.queryParams.pageNum > 1)
        this.queryParams.pageNum--;
      this.getEmployeeList();
      this.$message.success("删除员工成功");
    },
    // 点击角色按钮弹出层
    async btnRole(id) {
      this.showRoleDialog = true;
      this.roleList = await getEnableRoleList();
      this.currentUserId = id;
      const { roleIdArray } = await getEmployeeDetail(id);
      this.roleIds = roleIdArray[0].split(',').map(roleId => parseInt(roleId, 10));

      console.log(roleIdArray);
    },
    btnRoleOK() {
      assignRole({
        id: this.currentUserId,
        // roleIdArray: this.roleIds.map((roleId) => String(roleId)),
        roleIdArray: this.roleIds.map((roleId) => String(roleId)).join(","),
      })
        .then(() => {
          console.log(this.roleIds.map((roleId) => String(roleId)));
          this.$message.success("分配用户角色成功");
          this.showRoleDialog = false;
          this.roleIds = [5]
        })
        .catch((error) => {
          console.error(error);
          this.$message.error("分配用户角色失败");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
